package com.hronline;

import java.util.ArrayList;

import yaochangwei.pulltorefreshlistview.widget.RefreshableListView;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;

import com.adapter.EmployeeDetailAdapter;
import com.delegate.ManagerEmployeesDelegate;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.makeramen.segmented.SegmentedRadioGroup;
import com.models.AbsenceSummary;
import com.models.EmergencyContact;
import com.models.Employees;
import com.models.Status;
import com.parser.ManagerParser;

public class EmployeeDetailActivity extends Fragment implements EmployeeDetailAdapterDelegate {
	
	public final int ABSENCE_TAB		=	1;
	public final int INFORMATION_TAB	=	2;
	public final int EMERGENCY_TAB		=	3;
	
	private EmployeeDetailAdapter adapter;
	private ProgressDialog loadingDialog;
	
	private String empId;
	private String empName;
	private Employees employeeInfo;
	private ArrayList<EmergencyContact> arrEmergency;
	private AbsenceSummary asbsenceSummary;
	
	private Context context;
	private ManagerEmployeesDelegate delegate;
	
	public EmployeeDetailActivity (Context context, ManagerEmployeesDelegate delegate, String employeeId, String employeeName){
		
		super();
		
		this.context	=	context;
		this.delegate	=	delegate;
		this.empId		=	employeeId;
		this.empName	=	employeeName;
	}
	
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		
		// TODO Auto-generated method stub
		View fragmentView	=	inflater.inflate(R.layout.activity_employee_detail, container, false);
		
		loadingDialog	=	new ProgressDialog(this.context);
		loadingDialog.setMessage(Constant.LOADING_STRING);
		
		createNavigationBar(fragmentView);
		setUpControl(fragmentView);
		
		requestData();
		return fragmentView;
	}
	
	
	/*=====================================================================*/
	/* INIT VIEW
	 * this section is used to init control on view
	 *  */
	
	/* this method is used to create navigation bar */
	private void createNavigationBar(View view){
		Button	btnBack	=	(Button)view.findViewById(R.id.btn_back_employees);
		btnBack.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				didClickBackButton();
			}
		});
		
		ImageButton btnCalendar	=	(ImageButton)view.findViewById(R.id.btnCalendar);
		btnCalendar.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				didClickCalendarButton();
			}
		});
	}
	
	/* this method is used to set up control on this view */
	private void setUpControl(View view){
		
		RefreshableListView empDetailList	=	(RefreshableListView)view.findViewById(R.id.employeesDetailListView);
		if(adapter == null){
			adapter	=	new EmployeeDetailAdapter(this.context, this);
			adapter.setTabToDisplay(ABSENCE_TAB);
		}
		empDetailList.setAdapter(adapter);
		
		
		SegmentedRadioGroup segment	=	(SegmentedRadioGroup)view.findViewById(R.id.segment_text);
		segment.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				// TODO Auto-generated method stub
				if(checkedId == R.id.button_one){//absence tab
					adapter.setTabToDisplay(ABSENCE_TAB);
					adapter.setAbsenceSummary(asbsenceSummary);
				}
				else if(checkedId == R.id.button_two){//information tab
					adapter.setTabToDisplay(INFORMATION_TAB);
					adapter.setEmployeeInfo(employeeInfo);
				}
				else if(checkedId == R.id.button_three){//emergency tab
					adapter.setTabToDisplay(EMERGENCY_TAB);
					adapter.setEmergencyList(arrEmergency);
				}
				
				adapter.notifyDataSetChanged();
			}
		});
	}
	
	/*=====================================================================*/
	/* SELECTOR
	 * this section is used to create selector for this view
	 *  */
	
	/* this method is used to handle when user click on the back button */
	private void didClickBackButton(){
		delegate.pop();
	}
	
	/* this method is used to handle when user click on calendar button */
	private void didClickCalendarButton(){
		
	}
	
	/* this method is used to request data from server */
	private void requestData(){
		
		if(this.employeeInfo == null){
			loadingDialog.show();
			
			getEmployeeAbsenceSummary(empId);
		}
		else{
			adapter.notifyDataSetChanged();
		}
	}

	/*=====================================================================*/
	/* DELEGATE */
	@Override
	public void didClickRequestAbsence() {
		// TODO Auto-generated method stub
		Log.i("duylept", "didClickRequestAbsence");
	}


	@Override
	public void didClickApproveAbsence() {
		// TODO Auto-generated method stub
		Log.i("duylept", "didClickApproveAbsence");
	}


	@Override
	public void didClickLogSickness() {
		// TODO Auto-generated method stub
		delegate.openLogSicknessPage(empName, empId);
	}


	@Override
	public void didClickLogLateness() {
		// TODO Auto-generated method stub
		delegate.openLogLatenessPage(empName, empId);
	}
	
	@Override
	public void callTheNumber(String telephone) {
		// TODO Auto-generated method stub
		Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(telephone)); 
        startActivity(callIntent);
	}
	
	@Override
	public void sendEmail(String emailAddressToSend) {
		// TODO Auto-generated method stub
		Intent i = new Intent(Intent.ACTION_SEND);
		i.setType("message/rfc822");
		i.putExtra(Intent.EXTRA_EMAIL  , new String[]{emailAddressToSend});
		i.putExtra(Intent.EXTRA_SUBJECT, "subject of email");
		i.putExtra(Intent.EXTRA_TEXT   , "body of email");
		try {
		    startActivity(Intent.createChooser(i, "Send mail..."));
		} catch (android.content.ActivityNotFoundException ex) {
		    Toast.makeText(this.context, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
		}
	}
	
	/*=====================================================================*/
	
	/* CALL API
	 * this section is used to call api to get data from sever
	 *  */
	
	/* this method is used to get employee absence summary */
	private void getEmployeeAbsenceSummary(String empId){
		String url	=	String.format("%sSummary/GetEmployeeHolidaySummary?AuthorisationToken=%s&employeeId=%s", Constant.SERVER_ADDRESS, Constant.AUTHORIZED_TOKEN, empId);
		
		AsyncHttpClient client	=	new AsyncHttpClient();
		client.get(url, new AsyncHttpResponseHandler(){
			
			@Override
			public void onSuccess(String content) {
				// TODO Auto-generated method stub
				super.onSuccess(content);
				handleEmployeeAbsenceSummarySuccess(content);
			}
			
			@Override
			public void onFailure(Throwable error, String content) {
				// TODO Auto-generated method stub
				super.onFailure(error, content);
				handleConnectionError();
			}
			
		});
	}
	
	/* this method is used to get employee information */
	private void getEmployeeInformation(String empId){
		String url	=	String.format("%sEmployee/GetEmployeeDetails?AuthorisationToken=%s&EmployeeId=%s", Constant.SERVER_ADDRESS, Constant.AUTHORIZED_TOKEN, empId);
		
		AsyncHttpClient client	=	new AsyncHttpClient();
		client.get(url, new AsyncHttpResponseHandler(){
			
			@Override
			public void onSuccess(String content) {
				// TODO Auto-generated method stub
				super.onSuccess(content);
				handleEmployeeInformationSuccess(content);
			}
			
			@Override
			public void onFailure(Throwable error, String content) {
				// TODO Auto-generated method stub
				super.onFailure(error, content);
				handleConnectionError();
			}
			
		});
	}
	
	/* this method is used to get emergency Contacts */
	private void getEmergencyContact(String empId){
		String url	=	String.format("%sEmployee/GetEmergencyContacts?AuthorisationToken=%s&employeeId=%s", Constant.SERVER_ADDRESS, Constant.AUTHORIZED_TOKEN, empId);
		
		AsyncHttpClient client	=	new AsyncHttpClient();
		client.get(url, new AsyncHttpResponseHandler(){
			
			@Override
			public void onSuccess(String content) {
				// TODO Auto-generated method stub
				super.onSuccess(content);
				handleEmployeeEmergencySuccess(content);
			}
			
			@Override
			public void onFailure(Throwable error, String content) {
				// TODO Auto-generated method stub
				super.onFailure(error, content);
				handleConnectionError();
			}
			
		});
	}
	
	
	/* this is method is used to get advice calling number */
	private void getAdviceNumber(String empId){
		String url	=	String.format("%sEmployee/GetAdviceNumber?AuthorisationToken=%s&employeeId=%s", Constant.SERVER_ADDRESS, Constant.AUTHORIZED_TOKEN, empId);
		
		AsyncHttpClient client	=	new AsyncHttpClient();
		client.get(url, new AsyncHttpResponseHandler(){
			
			@Override
			public void onSuccess(String content) {
				// TODO Auto-generated method stub
				super.onSuccess(content);
				handleGetAdviceNumberSuccess(content);
			}
			
			@Override
			public void onFailure(Throwable error, String content) {
				// TODO Auto-generated method stub
				super.onFailure(error, content);
				handleConnectionError();
			}
			
		});
	}
	
	/*=====================================================================*/
	/* HANDLE API MESSAGE RETURN 
	 * this method is used to handle when call api
	 * */
	
	/* this method is used to handle when get employee absence summary success */
	private void handleEmployeeAbsenceSummarySuccess(String result){
		
		ArrayList<Object> arrResult	=	ManagerParser.parseEmployeeSummaryAbsence(result);
		
		/* get status object */
		Status statusItem	=	(Status)arrResult.get(0);
		if(!isStatusError(statusItem, "getEmployeeAbsenceSummary")){
			
			asbsenceSummary	=	(AbsenceSummary)arrResult.get(1);
			adapter.setAbsenceSummary(asbsenceSummary);
			adapter.notifyDataSetChanged();
			getEmployeeInformation(empId);
		}
		
	}
	
	/* this method is used to handle when get employee information success */
	private void handleEmployeeInformationSuccess(String result){
		ArrayList<Object> arrResult	=	ManagerParser.parseEmployeeInformation(result);
		
		/* get status object */
		Status statusItem	=	(Status)arrResult.get(0);
		if(!isStatusError(statusItem, "getEmployeeInformation")){
			employeeInfo	=	(Employees)arrResult.get(1);
			adapter.setEmployeeInfo(employeeInfo);
			getEmergencyContact(empId);
		}
	}
	
	/* this method is used to handle when get employee emergency success */
	@SuppressWarnings("unchecked")
	private void handleEmployeeEmergencySuccess(String result){
		ArrayList<Object> arrResult	=	ManagerParser.parseEmployeeEmergency(result);
		
		/* get status object */
		Status statusItem	=	(Status)arrResult.get(0);
		if(!isStatusError(statusItem, "getEmployeeEmergency")){
			
			arrEmergency	=	(ArrayList<EmergencyContact>)arrResult.get(1);
			adapter.setEmergencyList(arrEmergency);
			
			getAdviceNumber(empId);
		}
		
	}
	
	/* this method is used to handle when get advice number success */
	private void handleGetAdviceNumberSuccess(String result){
		ArrayList<Object> arrResult	=	ManagerParser.parseEmployeeAdviceNumber(result);
		
		/* get status object */
		Status statusItem	=	(Status)arrResult.get(0);
		if(!isStatusError(statusItem, "getAdviceNumber")){
			
			String adviceNumber	=	(String)arrResult.get(1);
			adapter.setAdviceNumber(adviceNumber);
			
			loadingDialog.dismiss();
			adapter.notifyDataSetChanged();
		}
	}
	
	/* this method is used to handle when connect to server error */
	private void handleConnectionError(){
		loadingDialog.hide();
		Constant.showErrorMessage(this.context, Constant.CANNOT_CONNECT_SERVER);
	}
	
	/* this method is used to check status return of sever */
	private boolean isStatusError(Status statusItem, String apiCalling){
		
		/* dismiss the loading dialog */
		loadingDialog.dismiss();
		
		if(statusItem.statusCode >= Constant.IVALID_AUTHORIZED_TOKEN){
			String message	=	String.format("%s - API %s", statusItem.getStatusText(), apiCalling);
			
			AlertDialog.Builder builder	=	new AlertDialog.Builder(this.context);
			builder.setMessage(message);
			builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					dialog.dismiss();
					delegate.openLoginPage();
				}
			});
			
			builder.show();
			
			return true;
		}
		
		return false;
	}
}
